<?php
/**
 * www.zhuizhan.com.
 * User: junyv
 * Date: 14-11-29 下午2:47
 */
namespace Admin\Controller;
use Think\Controller;
use Org\Yike\Tree;
use Org\Yike\Rights;
class RoleController extends CommonController{
    public function _initialize(){
        parent::_initialize();
    }
    public function _before_index(){
        //$this->list_relation = true;
        $big_menu = array(
            'title' => '添加角色',
            'iframe' => U('Role/add'),
            'id' => 'add',
            'width' => '450',
            'height' => '190',
        );
        $this->roleid = session('roleid');
        $this->superroleid = C('SUPERADMIN_ROLEID');
        $this->assign('big_menu', $big_menu);
    }
    public function editmenu(){
        $tree = new Tree();
        $tree->icon = array('│ ','├─ ','└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $result =  F('managemenu'.session('roleid'));//M('menu')->order('ordid')->select();
        $array = array();
        $roleid = I('get.id');
        //读取权限表
        $menu = M('role_menu')->where(array('roleid'=>$roleid))->field('id')->select();
        $menuarr = array();
        if($menu){
            foreach($menu as $v){
                $menuarr[] = $v['id'];
            }
        }
        foreach($result as $r) {
            $r['parentid_node'] = ($r['pid'])? ' class="child-of-node-'.$r['pid'].'"' : '';
            $r['cname'] = L($r['name']);
            $r['checked'] = in_array($r['id'],$menuarr) ? 'checked' : '';
            $array[] = $r;
        }
        $str  = "<tr id='node-\$id' \$parentid_node>
                <td align='center' width='1'></td>
                <td><input type='checkbox' name='menuid[]' value='\$id' \$checked class='J_checkitem'>\$spacer\$name</td>
                </tr>";
        $tree->init($array);
        $menu_list = $tree->get_tree(0, $str);
        $this->roleid = $roleid;
        $this->assign('list', $menu_list);
        $res = $this->fetch();
        $this->ajaxReturn(1,'',$res);
    }
    public function setrule(){
        $idarr = I('request.menuid');
        $roleid = I('request.role_id');
        $obj   = M('menu');
        $rolemenu = M('role_menu');
        if($idarr){
            //删除原有的权限
            $rolemenu->where('roleid='.$roleid)->delete();
            //复制数据到角色权限表
            $ids = implode(',',$idarr);
            $lists = $obj->where(array('id'=>array('in',$ids)))->select();
            foreach($lists as $k=>$v){
                $lists[$k]['roleid'] = $roleid;
                //$lists[$k]['menuid'] = $v['id'];
                //unset($lists[$k]['id']);
            }
            if($rolemenu->addAll($lists)){
                F('managemenu'.$roleid,$lists);//缓存权限文件
                $this->ajaxReturn(1,'成功','成功','edit');
            }else{
                $this->ajaxReturn(0,'失败','失败','edit');
            }
        }else{
            $this->ajaxReturn(0,'请至少选择一项','请至少选择一项','edit');
        }
    }
}